package com.shaoshaohuo.app;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/6/8.
 */

public class BigbitmapUtils {

//aaaaa


    private static Handler handler = new Handler();
    private static ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    private static Map<String, SoftReference<byte[]>> map = new HashMap<>();
    private static LruCache<String, byte[]> lruCache = new LruCache<String, byte[]>((int) (Runtime.getRuntime().maxMemory() / 8)) {
        @Override
        protected int sizeOf(String key, byte[] value) {
            int byteCount = value.length;// 获取图片占用内存大小
            return byteCount;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, byte[] oldValue, byte[] newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);
            map.put(key, new SoftReference<byte[]>(oldValue));
        }
    };


    public static void BigImage(final String urpaht, final Context context, final LinearLayout linearLayout) {

        linearLayout.removeAllViews();
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {

                    if (lruCache.get(urpaht) != null) {
                        Log.e("TAG", "run: 内存缓存");
                        final List<Bitmap> rectbitmap = rectbitmap(context, lruCache.get(urpaht));
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < rectbitmap.size(); i++) {
                                    ImageView imageView = new ImageView(context);
                                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                    imageView.setImageBitmap(rectbitmap.get(i));
                                    //
                                    Log.e("TAG", "run: ++++++++++++++++++++++++" + (float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth());
                                    linearLayout.addView(imageView);
                                    imageView.setLayoutParams(new LinearLayout.LayoutParams(context.getResources().getDisplayMetrics().widthPixels, (int) (rectbitmap.get(i).getHeight() * ((float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth()))));
                                    imageView.setBackgroundColor(Color.RED);
                                }

                            }
                        });
                    } else if (map.get(urpaht) != null && map.get(urpaht).get() != null) {
                        Log.e("TAG", "run: 软引用");
                        lruCache.put(urpaht, map.get(urpaht).get());
                        final List<Bitmap> rectbitmap = rectbitmap(context, map.get(urpaht).get());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < rectbitmap.size(); i++) {
                                    ImageView imageView = new ImageView(context);
                                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                    imageView.setImageBitmap(rectbitmap.get(i));
                                    //
                                    Log.e("TAG", "run: ++++++++++++++++++++++++" + (float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth());
                                    linearLayout.addView(imageView);
                                    imageView.setLayoutParams(new LinearLayout.LayoutParams(context.getResources().getDisplayMetrics().widthPixels, (int) (rectbitmap.get(i).getHeight() * ((float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth()))));
                                    imageView.setBackgroundColor(Color.RED);
                                }

                            }
                        });
                    } else {
                        Log.e("TAG", "run: 网络");
                        URL url = new URL(urpaht);
                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                        urlConnection.setRequestMethod("GET");
                        urlConnection.setConnectTimeout(5000);
                        if (urlConnection.getResponseCode() == 200) {
                            InputStream inputStream = urlConnection.getInputStream();
                            int len = 0;
                            byte[] buffer = new byte[1024 * 2];
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            while ((len = inputStream.read(buffer)) != -1) {
                                byteArrayOutputStream.write(buffer, 0, len);

                            }
                            byte[] reclkbitmap = reclkbitmap(byteArrayOutputStream.toByteArray(), context);
                            lruCache.put(urpaht, reclkbitmap);
                            final List<Bitmap> rectbitmap = rectbitmap(context, reclkbitmap);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < rectbitmap.size(); i++) {
                                        ImageView imageView = new ImageView(context);
                                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                        imageView.setImageBitmap(rectbitmap.get(i));
                                        //
                                        Log.e("TAG", "run: ++++++++++++++++++++++++" + (float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth());
                                        linearLayout.addView(imageView);
                                        imageView.setLayoutParams(new LinearLayout.LayoutParams(context.getResources().getDisplayMetrics().widthPixels, (int) (rectbitmap.get(i).getHeight() * ((float) context.getResources().getDisplayMetrics().widthPixels / (float) rectbitmap.get(i).getWidth()))));
                                        imageView.setBackgroundColor(Color.RED);
                                    }

                                }
                            });


// BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
//                        int height = bitmapRegionDecoder.getHeight();
//                        if (height > context.getResources().getDisplayMetrics().heightPixels) {
//                            //需要裁剪的高度
//                            int i = height - context.getResources().getDisplayMetrics().heightPixels;
//                            BitmapFactory.Options options = new BitmapFactory.Options();
//                            Rect rect = new Rect();
//                            rect.set(0, 0, bitmapRegionDecoder.getWidth(), context.getResources().getDisplayMetrics().widthPixels);
//                            final Bitmap bitmap = bitmapRegionDecoder.decodeRegion(rect, options);
//
//                        }
                        }
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //大图分割
    public static List<Bitmap> rectbitmap(Context context, byte[] bytes) {
        List<Bitmap> floats = new ArrayList<>();
        int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
        int heightPixels = context.getResources().getDisplayMetrics().heightPixels;

        //正常手机
        try {
            BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(bytes, 0, bytes.length, false);
            int height = bitmapRegionDecoder.getHeight();
            int width = bitmapRegionDecoder.getWidth();
            int i = height % widthPixels;
            int veryonebtheight = height / widthPixels;
            if (i > 0) {
                i = 1;
            }
            int size = veryonebtheight + i;
            Log.e("TAG", "rectbitmap: " + size + "height" + height + "widthPixels" + widthPixels + "veryonebtheight" + veryonebtheight);
            for (int c = 0; c < size; c++) {
                height -= widthPixels;
                if (c != size - 1) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    Rect rect = new Rect();
                    rect.set(0, widthPixels * c, width, widthPixels * c + widthPixels);
                    Bitmap bitmap = bitmapRegionDecoder.decodeRegion(rect, options);
                    floats.add(bitmap);
                } else {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    Rect rect = new Rect();
                    rect.set(0, widthPixels * c, width, bitmapRegionDecoder.getHeight());
                    Bitmap bitmap = bitmapRegionDecoder.decodeRegion(rect, options);
                    floats.add(bitmap);
                }

            }

            return floats;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return floats;
    }

    public static byte[] reclkbitmap(byte[] bitmap, Context context) {
        int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length, options);
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        int simpesize = 1;
        while (outWidth / simpesize > widthPixels) {
            simpesize *= 2;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = simpesize;
        Bitmap bitmap1 = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length, options);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        if(bitmap1!=null){
            bitmap1.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
        }

        byte[] bytes = byteArrayOutputStream.toByteArray();
        return bytes;
    }
}
